using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections.Specialized;

namespace StateTheater.Models
{
	public class jqGridPacket<T>
	{
		public jqGridPacket()
		{
			this.page = 0;
			this.records = 0;
			this.rows = new T[0];
			this.total = 0;
		}

		public jqGridPacket(IEnumerable<T> coll)
		{
			if (coll != null)
			{
				this.rows = coll as T[];
				if (this.rows == null)
				{
					this.rows = coll.ToArray();
				}

				this.total = 1;
				this.page = 1;
				this.records = this.rows.Length;
			}

		}
		public int total { get; set; }
		public int page { get; set; }
		public int records { get; set; }
		public T[] rows { get; set; }
	}

	public class jqGridPager
	{
		public int Page { get; set; }
		public int Rows { get; set; }
		public int Skip { get { return (Page - 1) * Rows; } }
		public string SortBy { get; set; }
		public string SortDirect { get; set; }
		public bool SortAsc { get; set; }

		public jqGridPager(NameValueCollection parms)
		{
			this.Page = Convert.ToInt32(parms["page"] ?? "1");
			this.Rows = Convert.ToInt32(parms["rows"] ?? "999");
			this.SortBy = parms["sidx"];
			this.SortDirect = parms["sord"] ?? "asc";
			this.SortAsc = SortDirect == "asc";
		}

		public IQueryable<T> AddPaging<T>(IQueryable<T> pending)
		{
			return pending.Skip(this.Skip).Take(this.Rows);
		}

		public void SetResponse<T>(jqGridPacket<T> packet, int count)
		{
			packet.page = this.Page;
			packet.records = count;
			packet.total = (packet.records + this.Rows - 1) / this.Rows;
		}

		public jqGridPacket<T> PackageResponse<T>(IEnumerable<T> coll, int totalCount)
		{
			var page = new jqGridPacket<T>(coll);
			//page.page = paging.Page;
			//page.records = db.FORUM_MEMBERs.Count();
			//page.total = (page.records + paging.Rows - 1) / paging.Rows;
			this.SetResponse(page, totalCount);
			return page;
		}
		public jqGridPacket<T> PackageResponse<T>(IQueryable<T> query)
		{
			int totalCount = query.Count();
			query = this.AddPaging(query);
			var page = new jqGridPacket<T>(query.ToList());
			this.SetResponse(page, totalCount);
			return page;
		}
	}



	public class jqFlexboxPacket<T>
	{
		public T[] results { get; set; }
		public int total { get; set; }
		public jqFlexboxPacket()
		{
			this.results= new T[0];
			this.total = 0;
		}

		public jqFlexboxPacket(IEnumerable<T> coll)
		{
			if (coll != null)
			{
				this.results = coll as T[];
				if (this.results == null)
				{
					this.results = coll.ToArray();
				}

				this.total = this.results.Length;
			}
		}
		
	}
}



